package com.dongdongshop.controller;

import com.dongdongshop.domain.AjaxResult;
import com.dongdongshop.em.ResultEnum;
import com.dongdongshop.pojo.TbAdmin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {

    // 当请求拦截的话,让他跳转到登录页面
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }



    @RequestMapping("login")
    @ResponseBody
    public AjaxResult login(TbAdmin admin){
        //shiro 登录
        //获取用户主体
        Subject subject = SecurityUtils.getSubject();
        //封装 token
        UsernamePasswordToken token = new UsernamePasswordToken(admin.getName(),admin.getPwd());
        //登录
        try {
            subject.login(token);
            return AjaxResult.OK();
        } catch (UnknownAccountException u) { //未知帐户异常
           return AjaxResult.R(ResultEnum.ACCOUNT_DOES_NOT);
        }catch (IncorrectCredentialsException i){ // 不正确的凭据异常
            return AjaxResult.R(ResultEnum.WRONG_PASSWORD);
        }
    }

    @RequestMapping("index")
    public String index(){
        return "admin/index";
    }
}
